package org.jeecg.common.wx;

import org.apache.commons.io.FilenameUtils;
import org.jeecg.common.api.vo.Result;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Random;

/**
 * @CLASSNAME UploadUtil
 * @DESCRIPTION 描述
 * @AUTHOR chen
 * @DATE 2018-12-04 14:52
 **/
public class UploadUtil {

    /**
     * 单文件上传
     *
     * @param file
     * @param paths
     * @return
     */
    public static Result upload(MultipartFile file, String paths) {
        Result<String> result = new Result<>();
        if (!file.isEmpty()) {
            String fileName = "";//文件名
            // 获取保存路径
            String path = paths;
            File f = new File(path);
            if (!f.exists()) {
                f.mkdirs();
            }
            // 原文件名
            String oldFileName = file.getOriginalFilename();
            // 文件后缀名
            String prefix = FilenameUtils.getExtension(oldFileName);
            // 文件大小
            long fileSize = 102400000L;
            // 判断文件大小是否符合要求
            if (file.getSize() > fileSize) {
                result.setSuccess(false);
                result.setMessage("文件过大，请重新上传");
                result.setCode(1);
            } else {
                assert prefix != null;
                if (prefix.equalsIgnoreCase("jpg") | prefix.equalsIgnoreCase("jpeg") | prefix.equalsIgnoreCase("gif") | prefix.equalsIgnoreCase("png") | prefix.equalsIgnoreCase("mp4")) {// 上传图片格式是否正确
                    // 设置新文件名
                    fileName = System.currentTimeMillis() + new Random().nextInt(1000000) + "." + prefix;
                    // 创建文件对象
                    File targetFile = new File(path, fileName);
                    // 保存
                    try {
                        file.transferTo(targetFile);
                    } catch (IllegalStateException | IOException e) {
                        e.printStackTrace();
                    }
//                    result.setResult("/image/" + fileName);
                    result.setResult("https://test.zhenyangzixun.com/enroll/image/" + fileName);//上传文件成功以后返回文件保存的路径
                } else {
                    result.setSuccess(false);
                    result.setMessage("文件格式不正确");
                    result.setCode(1);
                }
            }
        } else {
            result.setSuccess(false);
            result.setMessage("上传的文件为空");
            result.setCode(1);
        }
        return result;
    }


}
